import os

from jinja2 import Template

from utils.str_utils import to_camel_case


def service_template_code(model_name, time_field):
    template_code = '''
from models.models_dev import {{model_name}} as Dev{{model_name}}
from models.models_prod import {{model_name}} as Prod{{model_name}}
from services.base_dev_common_service import BaseDevCommonService
from utils.obj_utils import ObjectUtil

class Dev{{model_name}}Service(BaseDevCommonService):
    def __init__(self, db_config_path='../envs/.env.dev'):
        super().__init__(model_class=Dev{{model_name}}, time_field='{{time_field}}', db_config_path=db_config_path)

    def add(self, prod_orders: list[Prod{{model_name}}],session=None):
        # 如果未提供session，则获取新的session
        if session is None:
            session = self.get_session()
        dev_orders = []
        for prod_order in prod_orders:
            dev_order = Dev{{model_name}}() # 创建 model 实例，dev 环境的
            ObjectUtil.copy_fields(dev_order, prod_order, self.get_table_fields({'id'}))
            dev_orders.append(dev_order)
        session.add_all(dev_orders)
        session.commit()
    '''
    template = Template(template_code)
    return template.render(model_name=to_camel_case(model_name), time_field=time_field)


def main_gen_service_code(model_name, time_field, out_path='../out'):
    service_code = service_template_code(model_name, time_field)
    with open(f'{out_path}/dev{model_name.replace("op", "").lower()}_service.py', 'w') as f:
        f.write(service_code)


def gen_service_code():
    from config.config import CONFIG
    tables = CONFIG.get('gen_code')['service']['gen_code_tables']
    if not tables:
        raise ValueError("Environment variable GEN_CODE_TABLES must be set.")
    try:
        service_out_path = CONFIG.get('gen_code')['service']['gen_code_service_out_pat']
    except Exception as e:
        print(e)
        service_out_path = '../out'
    # 如果文件不存在，则创建
    os.makedirs(service_out_path, exist_ok=True)
    print(tables)
    for table in tables.split(','):
        print(to_camel_case(table))
        service_name = table
        service_time_field = 'create_time'
        main_gen_service_code(service_name, service_time_field, service_out_path)
    print(f'生成完成,service 路径 {service_out_path}')


if __name__ == '__main__':
    gen_service_code()
    print("代码已生成,注意检查:\n1,时间区间的字段是否正确.\n2,模型赋值时,排除的字段是否正确")